package com.share.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class DingDingUtil {
    private final static String SECRET = "SECf39d7441b435b71771bcd156dead61625868650aaf88ba9192a82fb4460e6140";
    private final static String TOKEN = "42fd504cccc4ef2492a8fbca746b3ef150dba416dcce8778d7d9a60981cc751d";
    private final static String URL = "https://oapi.dingtalk.com/robot/send?access_token=%s&sign=%s&timestamp=%s";

    public static void main(String[] args) {
//        String body = "{\"combinedCostId\":\"OT613089372829728769\",\"globalTraceId\":\"vp613089377408205312\",\"reqData\":{\"bankCard\":\"null\",\"customerName\":\"梅宁\",\"extendInfoMap\":{\"wtSignFileUrl\":\"1\",\"eduBackground\":\"-1\",\"licenseNo\":\"914403001921965612\",\"vaTaxY\":\"1\",\"idCard\":\"513426199212028723\",\"companyName\":\"龙发科技公司\",\"purcpreCreditMoney\":\"-1\",\"certAddress\":\"深圳市桃园龙发科技公司\",\"coPreCreditMoney\":215515.33,\"orgType\":\"QIYE\",\"businessCity\":\"广州\",\"idValStartTime\":\"20210303\",\"taxableTurnoverY\":\"1\",\"legalYearIncome\":\"66666.22\",\"connectName2\":\"李武\",\"connectName1\":\"李武\",\"businessStreet\":\"拾破烂\",\"bankCardNo\":\"-1\",\"coDrawPreCreditMoney\":145565.22,\"enterpriseTakings\":99999.99,\"purcScore\":\"-1\",\"reqSeq\":\"-1\",\"customerName\":\"梅宁\",\"bankPhone\":\"19965653232\",\"businessAddressDetail\":\"A栋-1层\",\"credType\":\"1\",\"phone\":\"13501550037\",\"registAddress\":\"-1\",\"declareAmount\":2000000,\"name\":\"梅宁\",\"bankCardName\":\"-1\",\"connectPersonType1\":\"-1\",\"connectPersonType2\":\"-1\",\"maritalStatus\":\"-1\",\"certificateType\":\"-1\",\"comeDate\":\"19965653232\",\"facePhoto\":\"1\",\"businessLicenseUrl\":\"1\",\"grantingFlowCode\":\"-1\",\"bankName\":\"-1\",\"industry\":\"-1\",\"hrSignFileUrl\":\"1\",\"enterpriseAccountNo\":\"-1\",\"busiAddress\":\"深圳市桃园龙发科技公司\",\"phoneNo\":\"13501550037\",\"connectPhone1\":\"13490272766\",\"connectPhone2\":\"14066666666\",\"idValEndTime\":\"20290303\",\"businessProvince\":\"广东\",\"coCreditScore\":\"-1\",\"certEndTime\":\"20290303\",\"idCardPhoto\":\"1\",\"staffs\":\"总裁\",\"cerito\":\"513426199212028723\",\"residenceStreet\":\"大冲\",\"purcCreditGrade\":\"-1\",\"address\":\"高新园\",\"certStartTime\":\"20210303\",\"bankCnapsCode\":\"-1\",\"certificateType2\":\"-1\",\"idCardPhotob\":\"1\",\"residenceAddressDetail\":\"花园1区3东202\",\"certificateType1\":\"-1\",\"coCreditGrade\":\"111\",\"sex\":\"1\",\"certificateNo2\":\"-1\",\"certificateNo1\":\"-1\",\"allTaxY\":\"1\",\"beginDate\":\"20210303\",\"taxGradeNow\":\"1\",\"registCounty\":\"-1\",\"enterpriseAccountName\":\"-1\",\"residenceCity\":\"深圳\",\"registCity\":\"-1\",\"faceVideo\":\"1\",\"registProvince\":\"-1\",\"residenceProvince\":\"深圳\",\"age\":\"51\"},\"facePhoto\":\"1\",\"hrSignFileUrl\":\"1\",\"idCard\":\"513426199212028723\",\"idCardPhoto\":\"1\",\"idCardPhotob\":\"1\",\"licenseNo\":\"914403001921965612\",\"partnerId\":\"200014\",\"phoneNo\":\"13501550037\",\"productCode\":\"jingyedai\",\"reportId\":\"613089377396011008\",\"sessionId\":\"OT613089372829728768\",\"userId\":\"1626338442825\",\"variableStr\":\"131\",\"wtSignFileUrl\":\"1\"},\"reqDate\":\"20220427163923\",\"reqFrom\":\"jingyedai\",\"serviceId\":\"355\"}";
//        sendMsg("泽浩", body);

        int i = 100;
        while (i-- > 0) {
            try {
                HttpUtil.get("https://www.hao123.com/api/citymenu?");
                System.out.println("Ss");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static Map<String, String> headers = new HashMap<>();

    static {
        headers.put("Content-Type", "application/json;charset=utf-8");
    }

    private static String getSign(String secret, long timespace) {
        String param = timespace + "\n" + secret;
        String sign = null;
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(param.getBytes("UTF-8"));
            sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
        } catch (Exception e) {
            log.error("签名异常", e);
        }
        return sign;
    }

    public static int sendMdMsg(String title, String content) {
        return sendMdMsg(title, content, TOKEN, SECRET);
    }

    /**
     * @param title
     * @param content 支持markdown语法才可以自动换行
     */
    public static int sendMdMsg(String title, String content, String _token, String _secret) {
        int re = -1;
        if (StringUtils.isNotBlank(content)) {
            //组装标准的钉钉请求参数
            Map<String, Object> mMap = new HashMap<>();
            mMap.put("msgtype", "markdown");
            Map<String, String> markMap = new HashMap<>();
            markMap.put("title", title);
            markMap.put("text", content);
            mMap.put("markdown", markMap);
            String jsonStr = JSON.toJSONString(mMap);

            String errmsg = null;
            try {
                Long timestamp = System.currentTimeMillis();
                String sign = getSign(_secret, timestamp);
                String reqUrl = String.format(URL, _token, sign, timestamp);
                String result = HttpUtil.post(reqUrl, jsonStr, headers);
                log.info("钉钉消息url={},result={}", reqUrl, result);
                JSONObject res = JSON.parseObject(result);
                String errcode = res.getString("errcode");
                errmsg = res.getString("errmsg");
                if ("0".equals(errcode)) {
                    re = 1;
                } else {
                    re = 0;
                }
            } catch (Exception e) {
                log.error("钉钉消息发送失败errmsg={}", errmsg, e);
                re = -2;
            }
        }
        return re;
    }
}
